<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模仿input中的placeholder属性特点</title>
    <style>
        .placeholderColor {
            color: #999;
        }

        .counter {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
    </style>
</head>

<body>
    <input type="text" class="search">
    <div class="counter">还可以输入15个字</div>
</body>
<script>
    const input = document.querySelector('.search');
    const counter = document.querySelector('.counter');
    let placeholderText = '搜索...';
    let maxLength = 15;

    input.value = placeholderText;
    input.classList.add('placeholderColor');

    input.addEventListener('focus', function () {
        if (this.value === placeholderText) {
            this.value = '';
            this.classList.remove('placeholderColor');
        }
    });

    input.addEventListener('blur', function () {
        if (this.value === '') {
            this.value = placeholderText;
            this.classList.add('placeholderColor');
        }
    });

    input.addEventListener('input', function () {
        let currentLength = this.value.length;
        if (currentLength > maxLength) {
            this.value = this.value.substring(0, maxLength);
            currentLength = maxLength;
        }

        let remain = maxLength - currentLength;
        counter.innerHTML = `还可以输入${remain}个字`;
    });
</script>

</html>